/**
 * 权限管理类
 */
import { StateType } from '@/common-typings';
import { types } from '@/utils/utils';

class PermissionManager {
  public systemPermission: any[] = [];

  public pagePermission: any[] = [];

  public pageResource: StateType = {};

  /**
   * 初始化权限
   * @param permission
   */
  initPermission(permission: any[]) {
    if (types(permission) === 'array') {
      const systemPermission: any[] = [];
      const pagePermission: any[] = [];
      const pageResource: StateType = {};
      this.getSystemData(permission, systemPermission);
      this.getPagePermission(permission, pagePermission, pageResource);
      this.systemPermission = systemPermission;
      this.pagePermission = pagePermission;
      this.pageResource = pageResource;
    }
  }

  /**
   * 获取系统权限
   * @param permission
   * @param list
   */
  getSystemData = (permission: any[], list: any[]) => {
    permission.forEach((pageItem: StateType) => {
      if (pageItem.menuId && pageItem.menuId.toString().length === 2) {
        list.push(pageItem.keyword);
      }
    });
  };

  /**
   * 获取页面权限
   * @param permission
   * @param list
   */
  getPagePermission = (permission: any[], list: any[], obj: StateType) => {
    permission.forEach((pageItem: StateType) => {
      if (
        pageItem.menuId &&
        (pageItem.menuId.toString().length === 4 || pageItem.menuId.toString().length === 6)
      ) {
        list.push(pageItem.keyword);
        const resourceList: any[] = [];
        if (pageItem.children && pageItem.children.length) {
          pageItem.children.forEach((item: StateType) => {
            if (item.menuId && item.menuId.toString().length === 8) {
              resourceList.push(item.keyword);
            }
          });
          this.getPagePermission(pageItem.children, list, obj);
        }
        obj[pageItem.keyword] = resourceList;
      } else if (pageItem.children && pageItem.children.length) {
        this.getPagePermission(pageItem.children, list, obj);
      }
    });
  };

  /**
   * 检测页面权限
   * @param pathname
   */
  checkPageAccess = (pathname: string) =>
    this.pagePermission.some((item: string) => item === pathname);

  /**
   * 检测页面功能权限
   * @param key
   * @param pathname
   */
  checkPageResource = (key: string, pathname = window.location.pathname) => {
    const pathList = this.pageResource[pathname];
    return pathList.some((item: string) => item === key);
  };

  static instance: any;

  static getInstance() {
    if (!this.instance) {
      this.instance = new PermissionManager();
    }
    return this.instance;
  }
}

export default PermissionManager.getInstance();
